<template>
  <el-upload
    action="#"
    list-type="picture-card"
    :auto-upload="false"
    :on-remove="handleRemove"
    :on-change="handleFileChange"
    :before-upload="beforeUpload"
    ref="uploadRef"
    :file-list="fileList"
  >
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><ZoomIn /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue';
import type { UploadFile } from 'element-plus';

const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref<UploadFile[]>([]);
const newPostImages = ref<File[]>([]);
const uploadRef = ref(null);

const emit = defineEmits(['imagesSelected']);

const handleRemove = (file: UploadFile) => {
  console.log("进入到了handleRemove");
  console.log("file:", file);
  console.log("fileList.value:", fileList.value);
  const index = fileList.value.findIndex(f => f.uid === file.uid);
  if (index > -1) {
    console.log("if条件也进入了 index:", index);
    fileList.value.splice(index, 1);
    newPostImages.value.splice(index, 1);
    console.log("newPostImages after removal:", newPostImages.value); // 添加这行日志
    updateLocalStorage(); // 确保在删除图片后更新 localStorage
  } else {
    console.log("file not found in fileList.value");
  }
}


const updateLocalStorage = () => {
  console.log("updateLocalStorage called"); // 添加这行日志
  if (newPostImages.value.length === 0) {
    console.log("Removing savedPostImages from localStorage"); // 添加这行日志
    localStorage.removeItem('savedPostImages');
  } else {
    const base64Images = newPostImages.value.map(file => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => resolve(e.target!.result as string);
        reader.onerror = (e) => reject(e);
        reader.readAsDataURL(file);
      });
    });

    Promise.all(base64Images).then((results) => {
      console.log("Updating savedPostImages in localStorage with:", results); // 添加这行日志
      localStorage.setItem('savedPostImages', JSON.stringify(results));
    }).catch((error) => {
      console.error('Error converting images to Base64:', error);
    });
  }
}




const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
}

const handleDownload = (file: UploadFile) => {
  console.log(file);
}

const handleFileChange = (file: UploadFile, fileListArray: UploadFile[]) => {
  console.log("handleFileChange called with fileList:", fileListArray);
  fileList.value = fileListArray.map(file => {
    return {
      ...file,
      raw: file.raw || file.raw instanceof File ? file.raw : new File([], file.name), // 确保 raw 属性存在
      uid: file.uid || `uid_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` // 生成唯一的 uid
    } as UploadFile; // 类型断言
  });
  newPostImages.value = fileList.value.map(file => {
    if (file.raw) {
      return file.raw;
    } else {
      console.error('File object does not contain raw property:', file);
      return null;
    }
  }).filter(file => file !== null) as File[];
  console.log('New post images:', newPostImages.value);

  // 触发事件传递 newPostImages.value
  emit('imagesSelected', newPostImages.value);
  console.log('Emitted selected images:', newPostImages.value);
}


const beforeUpload = (file: UploadFile) => {
  // 文件上传前的验证逻辑
  return true;
}

const emitSelectedImages = () => {
  emit('imagesSelected', newPostImages.value);
  console.log('Emitted selected images:22222', newPostImages.value);
}

const dataURLtoBlob = (dataURL: string) => {
  const arr = dataURL.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}


onMounted(() => {
  const savedImages = localStorage.getItem('savedPostImages');
  if (savedImages) {
    const base64Images = JSON.parse(savedImages);
    base64Images.forEach((base64Image: string, index: number) => {
      const blob = dataURLtoBlob(base64Image);
      const file = new File([blob], `image_${index}.png`, { type: 'image/png' });
      const uploadFile: UploadFile = {
        name: file.name,
        url: URL.createObjectURL(file),
        status: 'ready',
        // raw: 9, // 确保 raw 属性存在
         uid:  index-1 //`uid_${Date.now()}_${Math.random().toString(36).substr(2, 9)}` // 生成唯一的 uid
      };
      fileList.value.push(uploadFile);
      newPostImages.value.push(file);
    });
  }
});
defineExpose({
  emitSelectedImages
});
</script>
